package com.weimai.flower.app.web;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import com.weimai.flower.app.entity.FlowerNameEntity;
import com.weimai.flower.app.service.FlowerNameService;
import com.weimai.flower.job.ImportJob;
import com.weimai.flower.util.PageDataVO;
import com.weimai.flower.util.PinyinUtil;
import com.weimai.flower.util.WmResult;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * Copyright (c) 2019 Choice, Inc.
 * All Rights Reserved.
 * Choice Proprietary and Confidential.
 *
 * 花名Controller
 *
 * @author yunhao
 * @since 2019-07-26 15:48
 */

@RestController
@RequestMapping(value = "/name/")
public class FlowerNameController {

    private static final Logger logger = LoggerFactory.getLogger(FlowerNameController.class);

    @Autowired
    private FlowerNameService flowerNameService;

    @RequestMapping(value = "/addName", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ApiOperation("添加花名")
    @ApiResponses({@ApiResponse(code = 200, message = "添加花名", response = String.class),
                   @ApiResponse(code = 300, message = "花名不可为空", response = String.class),
                   @ApiResponse(code = 310, message = "花名已存在", response = String.class),
                   @ApiResponse(code = 320, message = "已有同读音的花名被使用", response = String.class)})
    public @ResponseBody
    WmResult<String> addName(@RequestParam("flowerName") String flowerName) {

        if (StringUtils.isEmpty(flowerName)) {
            return WmResult.success(300,"","花名不可为空!");
        }

        String spell = PinyinUtil.getPinYin(flowerName);

        FlowerNameEntity sameFlowerNameEntity = flowerNameService.getByName(flowerName);

        if (sameFlowerNameEntity!=null) {
            if(sameFlowerNameEntity.isUseFlag()){
                return WmResult.success(310,"","花名已存在!");
            }else{
                flowerNameService.setUsed(sameFlowerNameEntity.getId());
                return WmResult.success("保存成功");
            }
        }else{

            List<FlowerNameEntity>  sameSpellEntityList = flowerNameService.getBySpell(spell);
            if(sameSpellEntityList!=null&&!sameSpellEntityList.isEmpty()){
                long useCount = sameSpellEntityList.stream().filter(fi->fi.isUseFlag()).count();
                if(useCount>0){
                    return WmResult.success(320,"","已有同读音的花名被使用!");
                }
            }
            flowerNameService.save(new FlowerNameEntity(flowerName, spell, true, new Date(), new Date()));
        }

        return WmResult.success("保存成功");
    }

    @RequestMapping(value = "/delete", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ApiOperation("删除花名")
    @ApiResponses({@ApiResponse(code = 200, message = "删除花名", response = String.class)})
    public @ResponseBody
    WmResult<String> delete(@RequestParam("id") int id) {

        flowerNameService.delete(id);
        return WmResult.success("删除成功");
    }

    @RequestMapping(value = "/setUsed", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ApiOperation("将花名设为已使用")
    @ApiResponses({@ApiResponse(code = 200, message = "将花名设为已使用", response = String.class)})
    public @ResponseBody
    WmResult<String> setUsed(@RequestParam("id") int id) {

        flowerNameService.setUsed(id);
        return WmResult.success("更新成功");
    }

    @RequestMapping(value = "/setUnused", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ApiOperation("将花名设为未使用")
    @ApiResponses({@ApiResponse(code = 200, message = "将花名设为已使用", response = String.class)})
    public @ResponseBody
    WmResult<String> setUnused(@RequestParam("id") int id) {

        flowerNameService.setUnused(id);
        return WmResult.success("更新成功");
    }

    @RequestMapping(value = "/isUsed", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public @ResponseBody
    @ApiOperation("花名是否已占用")
    @ApiResponses({@ApiResponse(code = 200, message = "花名是否已占用", response = String.class),
                   @ApiResponse(code = 300, message = "花名不可为空", response = String.class),})
    WmResult<Boolean> isUsed(@RequestParam("flowerName") String flowerName) {

        if(StringUtils.isEmpty(flowerName)){
            return WmResult.success(300,false,"花名不可为空");
        }

        String spell = PinyinUtil.getPinYin(flowerName);

        boolean isExist = flowerNameService.isExist(flowerName,spell);

        return WmResult.success(isExist);
    }

    @RequestMapping(value = "/search", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public @ResponseBody
    @ApiOperation("搜索花名列表(分页)")
    @ApiImplicitParam(name="useFlag",paramType = "query" ,value="是否被使用,-1则查全部，0是未使用，1是已使用",defaultValue = "-1")
    @ApiResponses({@ApiResponse(code = 200, message = "搜索花名列表(分页)", response = String.class)})
    WmResult<PageDataVO> search(@RequestParam("word") String word,
                                @RequestParam(value = "useFlag", defaultValue = "-1") int useFlag ,
                                @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                                @RequestParam(value = "currentPage", defaultValue = "1") int currentPage) {

        List<FlowerNameEntity> dataList = flowerNameService.getList(word,useFlag, pageSize, currentPage);
        int count = flowerNameService.getCount(word,useFlag);

        int totalPage = (count/pageSize)+1;

        return WmResult.success(new PageDataVO(totalPage, (long)count, dataList));
    }

    @RequestMapping(value = "/getList", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ApiOperation("查询花名列表")
    @ApiImplicitParam(name="useFlag",paramType = "query" ,value="是否被使用,-1则查全部，0是未使用，1是已使用",defaultValue = "-1")
    @ApiResponses({@ApiResponse(code = 200, message = "查询花名列表", response = String.class)})
    public @ResponseBody
    WmResult<PageDataVO> getList(@RequestParam(value = "useFlag", defaultValue = "-1") int useFlag ,
                                 @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                                             @RequestParam(value = "currentPage", defaultValue = "1") int currentPage) {

        List<FlowerNameEntity> dataList = flowerNameService.getList(null,useFlag,pageSize, currentPage);

        int count = flowerNameService.getCount(null,useFlag);

        int totalPage = (count/pageSize)+1;

        return WmResult.success(new PageDataVO(totalPage, (long)count, dataList));
    }

    @RequestMapping(value = "/random", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    public @ResponseBody
    @ApiOperation("随机获取几个未使用的花名")
    @ApiResponses({@ApiResponse(code = 200, message = "随机获取几个未使用的花名", response = String.class)})
    WmResult<List<FlowerNameEntity>> random(@RequestParam(value = "size", defaultValue = "10") int limit) {

        List<FlowerNameEntity> dataList = flowerNameService.getRandomList(limit);
        return WmResult.success(dataList);
    }

    /**
     * @param file
     */
    @RequestMapping(value = "/importExcel", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    @ApiOperation("导入花名excel")
    @ApiResponses({@ApiResponse(code = 200, message = "导入花名excel", response = String.class),
                   @ApiResponse(code = 300, message = "导入失败!", response = String.class)})
    public WmResult<String> importFile(MultipartFile file) throws IOException {

        String fileName = file.getOriginalFilename();

        Workbook workBook = null;
        if (fileName.contains(".xlsx")) {
            workBook = new XSSFWorkbook(file.getInputStream());
        } else if (fileName.contains(".xls")) {
            workBook = new HSSFWorkbook(file.getInputStream());
        } else {
            return WmResult.success(300, "","上传文件格式不正确!");
        }

        try{
            Sheet sheet = workBook.getSheetAt(0);
            int lastRowNum = sheet.getLastRowNum();

            String text = sheet.getRow(0).getCell(0).getStringCellValue();
            if(StringUtils.isEmpty(text)||!"姓名".equals(text)){
                return WmResult.success(300, "","上传文件格式不正确!");
            }

            if(lastRowNum>0){
                for (int i = 1; i <= lastRowNum; i++) {
                    Row row = sheet.getRow(i);
                    String flowerName = row.getCell(0).getStringCellValue();
                    String spell = PinyinUtil.getPinYin(flowerName);
                    if(!StringUtils.isEmpty(flowerName)){
                        ImportJob.queue.offer(new FlowerNameEntity(flowerName, spell, true, new Date(), new Date()));
                    }
                }//end foreach
            }

        }catch (Exception e){
            return WmResult.error(300,"上传失败");
        }finally {
            // 5.关闭资源
            workBook.close();
        }

        return WmResult.success("上传成功!");
    }

    @RequestMapping(value = "/exportExcel",  produces = "application/octet-stream", method = RequestMethod.GET)
    @ApiOperation("导出花名excel")
    @ApiImplicitParam(name="useFlag",paramType = "query" ,value="是否被使用,-1则查全部，0是未使用，1是已使用",defaultValue = "-1")
    @ApiResponses({@ApiResponse(code = 200, message = "导出花名excel", response = String.class)})
    public void exportExcel(@RequestParam(value = "useFlag", defaultValue = "-1") int useFlag ,
                     HttpServletResponse response) {

        Workbook workbook = new HSSFWorkbook();

        String fileName = "所有花名册";
        if(useFlag==0){
            fileName = "微脉未使用花名册";
        }else if(useFlag==1){
            fileName = "微脉已使用花名册";
        }

        String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());

        try {

            HSSFSheet sheet = (HSSFSheet)workbook.createSheet("花名信息");

            List<FlowerNameEntity> dataList = flowerNameService.getAll(useFlag);

            HSSFRow row_first = sheet.createRow(0);
            Cell cell_first = row_first.createCell(0);
            cell_first.setCellValue("姓名");

            int rowNum = 1;

            for (FlowerNameEntity entity : dataList) {
                HSSFRow row = sheet.createRow(rowNum);
                Cell cell = row.createCell(0);
                cell.setCellValue(entity.getFlowerName());
                rowNum++;
            }

            String realFileName =  fileName+"_"+date+".xls";

            response.setContentType("application/octet-stream");
            response.setHeader("Content-disposition", "attachment;filename="+ URLEncoder.encode(realFileName, "utf-8"));//默认Excel名称
            response.flushBuffer();
            workbook.write(response.getOutputStream());

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
